package org.example.huweb.exception_advice;

import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.example.Result.Result;
import org.example.Result.ResultUtils;
import org.example.Result.StatusCode;
import org.example.exception.BusinessException;
import org.example.exception.BusinessExceptionEnum;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 *  异常拦截
**/
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 自定义业务异常拦截
     * BusinessException
     */
    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public Result<?> businessperson(BusinessException e) {
        log.info("业务异常拦截 {}", e.getMessage());
        return new Result<>(e.getStatus(), false, e.getMessage(), null);
    }

    @ExceptionHandler(ExpiredJwtException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public Result<?> businessperson(ExpiredJwtException e) {
        log.info(" JWT 登录过期请重新登录 {}", e.getMessage());
        return ResultUtils.unauthorized("登录过期请重新登录");
    }

    @ExceptionHandler(HttpMessageNotReadableException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public Result<?> businessperson(HttpMessageNotReadableException e) {
        log.info(" 数据异常 {}", e.getMessage());
        return ResultUtils.missingParameter("缺少数据");
    }


    /**
     * 未知的运行时异常拦截
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public Result<?> notFount(RuntimeException e) {
        log.info("____________________未知的运行时异常拦截____________________");

        log.error("{}", e.getMessage());
        log.error("{}", e.getClass());

        log.info("________________________________________________________");
        return ResultUtils.uncertain(e.getMessage());
    }


}

